<template>
    <div>
        <!-- 搜索表单 -->
        <el-form :model="searchForm" ref="searchFormRef" label-width="100px" class="search-form">
            <el-row>
                <el-col :span="24 / 3">
                    <el-form-item label="交易号">
                        <el-input v-model="searchForm.transactionId" placeholder="请输入交易号" />
                    </el-form-item>
                </el-col>
                <el-col :span="24 / 3">
                    <el-form-item label="用户类型">
                        <el-select v-model="searchForm.userType" placeholder="请选择用户类型">
                            <el-option label="全部" value="all" />
                            <el-option label="用户" value="user" />
                            <el-option label="商家" value="merchant" />
                            <el-option label="骑手" value="rider" />
                            <el-option label="站点" value="station" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24 / 3">
                    <el-form-item label="申请人">
                        <el-input v-model="searchForm.applicant" placeholder="请输入申请人" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="24 / 3">
                    <el-form-item label="手机号码">
                        <el-input v-model="searchForm.phone" placeholder="请输入手机号码" />
                    </el-form-item>
                </el-col>
                <el-col :span="24 / 3">
                    <el-form-item label="银行卡号">
                        <el-input v-model="searchForm.bankCardNumber" placeholder="请输入银行卡号" />
                    </el-form-item>
                </el-col>
                <el-col :span="24 / 3">
                    <el-form-item label="申请时间">
                        <el-select v-model="searchForm.applyTime" placeholder="请选择申请时间">
                            <el-option label="近三个月" value="lastThreeMonths" />
                            <el-option label="今年内" value="thisYear" />
                            <el-option label="2024" value="2024" />
                            <el-option label="2023" value="2023" />
                            <el-option label="2022" value="2022" />
                            <el-option label="2022年之前" value="before2022" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24 / 3">
                    <el-form-item label="提现状态">
                        <el-select v-model="searchForm.status" placeholder="请选择提现状态">
                            <el-option label="全部" value="all" />
                            <el-option label="提现中" value="inProgress" />
                            <el-option label="提现成功" value="success" />
                            <el-option label="提现失败" value="failed" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="2">
                    <el-form-item>
                        <el-button type="primary" @click="search">搜索</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="2">
                    <el-form-item>
                        <el-button type="info" @click="reset">重置</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <!-- 靠左的表格区域表格区域导出，设置 -->
        <div style="display: flex; justify-content: center; margin-top: 20px;">
            <el-button type="primary" @click="exportSelect" class="custom-button-primary">导出</el-button>
            <el-button type="info" @click="settingGO" class="custom-button-info">设置</el-button>
        </div>
        <!-- 弹窗区域 -->
        <el-dialog :title="title" :visible.sync="dialogFormVisible" width="60%">
            <span class="label">交易号:</span>
            <span>{{ finance.transactionId }}</span><br><br>
            <span class="label">提现状态:</span>
            <span>{{ getStatusText(finance.status) }}</span><br><br>
            <span class="label">用户类型:</span>
            <span>{{ statusText() }}</span><br><br>
            <span class="label">申请人:</span>
            <span>{{ finance.applicantName }}</span><br><br>
            <span class="label">手机号码:</span>
            <span>{{ finance.phone }}</span><br><br>
            <span class="label">提现方式:</span>
            <span>{{ getWithdrawalMethodText(finance.withdrawalMethod) }}</span><br><br>
            <span class="label">开户银行:</span>
            <span>{{ finance.bankName }}</span><br><br>
            <span class="label">银行卡号:</span>
            <span>{{ finance.bankCardNumber }}</span><br><br>
            <span class="label">预留手机号:</span>
            <span>{{ finance.preferredPhone }}</span><br><br>
            <span class="label">提现金额:</span>
            <span>{{ formatCurrency(null, null, finance.withdrawalAmount) }}</span><br><br>
            <span class="label">手续费:</span>
            <span>{{ formatCurrency(null, null, finance.handling_charge) }}</span><br><br>
            <span class="label">打款金额:</span>
            <span>{{ formatCurrency(null, null, finance.actualAmount) }}</span><br><br>
            <span class="label">申请时间:</span>
            <span>{{ finance.createTime }}</span><br><br>
            <div class="processing-opinion" v-if="finance.status === 1">
                <div style="border-top: 1px solid #e9e9e9;"></div>
                <span class="label" >处理意见:</span>
                <div class="opinion-content">
                    <span class="opinion-label">当前处理人:</span>
                    <span>周财务</span><br><br>
                    <el-radio-group v-model="finance.paymentResult">
                        <el-radio label=1 value=1>打款成功</el-radio>
                        <el-radio label=0 value=0>打款失败</el-radio>
                    </el-radio-group><br><br>
                    <el-tooltip content="下拉菜单可在系统配置->Dictionary配置中编辑" placement="top">
                        <el-input v-model="finance.failureReason" placeholder="请输入原因" :disabled="finance.paymentResult!== '0'"/>
                    </el-tooltip><br><br>
                    <el-input v-model="finance.supplementaryRemarks" placeholder="请输入补充说明"  :disabled="finance.paymentResult!== '0'"/>
                    <!-- 取消和确定的按钮 -->
                     <div style="display: flex; justify-content: flex-end; margin-top: 20px;">
                        <el-button type="primary" @click="dialogFormVisible = false">关闭</el-button>
                        <el-button type="success" @click="updateFinance(finance.transactionId)">确 定</el-button>
                    </div>
                </div>
            </div>
            <div class="processing-opinion" v-if="finance.status === 2">
                <span class="label">处理人:</span>
                <span>周财务</span><br><br>
                <span class="label">打款结果:</span>
                <span style="font-weight: bold">打款成功</span><br><br>
                <span class="label">申请时间:</span>
                <span>{{ finance.processTime }}</span><br><br>
            </div>
            <div class="processing-opinion" v-if="finance.status === 3">
                <span class="label">处理人:</span>
                <span>周财务</span><br><br>
                <span class="label">打款结果:</span>
                <span style="font-weight: bold">打款失败</span><br><br>
                <span class="label">失败原因:</span>
                <span>{{ finance.failureReason }}</span><br><br>
                <span class="label">处理时间:</span>
                <span>{{ finance.processTime }}</span><br><br>
            </div>
        </el-dialog>
        <!-- 弹窗区域2 -->
        <el-dialog :title="title" :visible.sync="dialogFormVisible2" width="60%">
            <div class="dialog-content">
                <p class="dialog-tip">可按用户类型设置手续费与提现限额，每次只能保存一个用户类型~</p>
                <el-form :model="withdrawalSettings" ref="withdrawalForm" :rules="rules" label-width="120px">
                <el-form-item label="用户类型" prop="userType">
                <el-radio-group v-model="withdrawalSettings.userType">
                    <el-radio label=1 value=1>用户</el-radio>
                    <el-radio label=2 value=2>商家</el-radio>
                    <el-radio label=3 value=3>骑手</el-radio>
                    <el-radio label=4 value=4>站点</el-radio>
                </el-radio-group>
                </el-form-item>
                <el-form-item label="提现费率" prop="withdrawalRate">
                <el-input-number v-model="withdrawalSettings.withdrawalRate" controls-position="left" :min="0" :max="100" :step="0.1"></el-input-number>
                <span>%</span>
                </el-form-item>
                <el-form-item label="单笔最低手续费" prop="minFeePerTransaction">
                <el-input-number v-model="withdrawalSettings.minFeePerTransaction" controls-position="left" :min="0"></el-input-number>
                <span>元</span>
                </el-form-item>
                <el-form-item label="单笔最高手续费" prop="maxFeePerTransaction">
                <el-input-number v-model="withdrawalSettings.maxFeePerTransaction" controls-position="left" :min="0" :step="10"></el-input-number>
                <span>元</span>
                </el-form-item>
                <el-form-item label="单笔最小限额" prop="minLimitPerTransaction">
                <el-input-number v-model="withdrawalSettings.minLimitPerTransaction" controls-position="left" :min="0"></el-input-number>
                <span>元</span>
                </el-form-item>
                <el-form-item label="单笔最大限额" prop="maxLimitPerTransaction">
                <el-input-number v-model="withdrawalSettings.maxLimitPerTransaction" controls-position="left" :min="0":step="1000"></el-input-number>
                <span>元</span>
                </el-form-item>
                <el-form-item label="每日限额" prop="dailyLimit">
                <el-input-number v-model="withdrawalSettings.dailyLimit" controls-position="left" :min="0" :step="1000"></el-input-number>
                <span>元</span>
                </el-form-item>
            </el-form>
            <div class="button-group">
                <el-button @click="dialogFormVisible2 = false">取消</el-button>
                <el-button type="primary" @click="handleSave">确定</el-button>
            </div>
            </div>
        </el-dialog>

        <!-- 账户列表区域 -->
        <el-table :data="rechargeList" style="width: 100%; margin-top: 10px" stripe>
            <el-table-column label="交易号" width="160">
                <template #default="scope">
                    <el-link @click="openPopup(scope.row.transactionId)">{{ scope.row.transactionId }}</el-link>
                </template>
            </el-table-column>
            <el-table-column prop="applicantName" label="申请人" width="100" />
            <el-table-column prop="withdrawalMethod" label="提现方式" width="120">
                <template #default="scope">
                    {{ getWithdrawalMethodText(scope.row.withdrawalMethod) }}
                </template>
            </el-table-column>
            <el-table-column prop="bankCardNumber" label="银行卡号" width="180">
                <template #default="scope">
                    <p>{{ scope.row.bankCardNumber }}</p>
                    <p>{{ scope.row.bankName }}</p>
                </template>
            </el-table-column>
            <el-table-column prop="phone" label="预留手机号" width="140" :formatter="formatPhone" />
            <el-table-column prop="withdrawalAmount" label="提现金额" width="100" :formatter="formatCurrency" />
            <el-table-column prop="actualAmount" label="打款金额" width="100" :formatter="formatCurrency" />
            <el-table-column prop="createTime" label="申请时间" width="140" />
            <el-table-column prop="processTime" label="处理时间" width="140" />
            <el-table-column prop="status" label="状态" width="80">
                <template #default="scope">
                    {{ getStatusText(scope.row.status) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
                <template #default="scope">
                    <el-dropdown v-if="scope.row.status === 1">
                        <span class="el-dropdown-link" style="font-weight: bold">
                            ...
                            <el-icon><caret-bottom /></el-icon>
                        </span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item @click="openPopup(scope.row.transactionId)">查看并处理</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            class="pagination"
        />
    </div>
</template>

<script>
import { ElMessage, getRechargeList, getRechargeOne,getRechargeUpdate,elMessage ,getRechargeAdd} from '@/api/withdrawalrecords';

export default {
    data() {
        return {
            userTypes: ['用户', '商家', '骑手', '站点'],
            withdrawalSettings: {
                userType: '',
                withdrawalRate: 3,
                minFeePerTransaction: 1,
                maxFeePerTransaction: 100,
                minLimitPerTransaction: 10,
                maxLimitPerTransaction: 4000,
                dailyLimit: 5000
            },
            searchForm: {
                transactionId: '',
                userType: '',
                applicant: '',
                phone: '',
                bankCardNumber: '',
                applyTime: '',
                status: ''
            },
            searchFormRef: null,
            rechargeList: [],
            currentPage: 1,
            pageSize: 10,
            total: 0,
            dialogFormVisible: false,
            dialogFormVisible2: false,
            title: '提现详情',
            finance: {
                transactionId: '',
                userType: '',
                applicantName: '',
                phone: '',
                bankName: '',
                bankCardNumber: '',
                withdrawalMethod: '',
                preferredPhone: '',
                withdrawalAmount: 0,
                handling_charge: 0,
                actualAmount: 0,
                createTime: '',
                processTime: '',
                status: '',
                paymentResult: '',
                failureReason: '',
                supplementaryRemarks: ''
            }
        };
    },
    created() {
        this.search();
    },
    methods: {
        search() {
            const params = {
                ...this.searchForm,
                pageNum: this.currentPage,
                pageSize: this.pageSize
            };
            getRechargeList(params)
              .then(res => {
                    this.rechargeList = res.data.records;
                    this.total = res.data.total;
                })
              .catch(error => {
                    ElMessage.error('查询失败，请稍后重试');
                    console.error('查询提现记录失败:', error);
                });
        },
        updateFinance(transactionId) {
            console.log(transactionId);
            const params = {
                transactionId: transactionId,
                paymentResult: this.finance.paymentResult,
                failureReason: this.finance.failureReason,
                supplementaryRemarks: this.finance.supplementaryRemarks
            };
            console.log(params);
            if (this.finance.paymentResult == '1') {
                console.log('打款成功');
                getRechargeUpdate(transactionId)
                .then(res => {
                        this.dialogFormVisible = false;
                        this.search();
                        ElMessage.success('处理成功');
                    })
                .catch(error => {
                        ElMessage.error('处理失败，请稍后重试');
                        console.error('处理提现记录失败:', error);
                    });
            }
            if (this.finance.paymentResult == '0') {
                console.log('打款失败');
                getRechargeAdd(params)
                    .then(res => {
                            this.dialogFormVisible = false;
                            this.search();
                            ElMessage.success('处理成功');
                    })
                    .catch(error => {
                            ElMessage.error('处理失败，请稍后重试');
                            console.error('处理提现记录失败:', error);
                    });
            }
        },
        exportSelect() {
            this.$confirm('确定要导出数据吗?', '信息', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                window.location.href='http://localhost:9020/api/withdrawalRecords/export';
            }).catch(() => {
                console.log('取消导出');
            });
        },
        settingGO() {
            this.dialogFormVisible2 = true;
        },
        handleSave() {
            const params = {
                        userType: this.withdrawalSettings.userType,
                        withdrawalRate: this.withdrawalSettings.withdrawalRate,
                        minFeePerTransaction: this.withdrawalSettings.minFeePerTransaction,
                        maxFeePerTransaction: this.withdrawalSettings.maxFeePerTransaction,
                        minLimitPerTransaction: this.withdrawalSettings.minLimitPerTransaction,
                        maxLimitPerTransaction: this.withdrawalSettings.maxLimitPerTransaction,
                        dailyLimit: this.withdrawalSettings.dailyLimit
                    };
            elMessage(params).then(() => {
                this.dialogFormVisible2 = false;
                ElMessage.success('保存成功');
            }).catch(() => {
                console.log('取消保存');
            });
        },
        statusText() {
            const userTypeMap = {
                1: '用户',
                2: '商家',
                3: '骑手',
                4: '站点'
            };
            return userTypeMap[this.finance.userType] || this.finance.status.toString();
        },
        reset() {
            this.searchForm = {
                transactionId: '',
                userType: '',
                applicant: '',
                phone: '',
                bankCardNumber: '',
                applyTime: '',
                status: ''
            };
            this.currentPage = 1;
            this.search();
        },
        formatCurrency(_, __, cellValue) {
            return `¥${cellValue}`;
        },
        formatPhone(_, __, cellValue) {
            return `+86 ${cellValue}`;
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.currentPage = 1;
            this.search();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.search();
        },
        openPopup(transactionId) {
            this.dialogFormVisible = true;
            getRechargeOne(transactionId)
              .then(res => {
                this.finance = {
                    rechargeId: res.data.withdrawalRecords.id,
                    transactionId: res.data.withdrawalRecords.transactionId,
                    userType: res.data.withdrawalRecords.userType,
                    applicantName: res.data.withdrawalRecords.applicantName,
                    phone: res.data.withdrawalRecords.phone,
                    bankName: res.data.withdrawalRecords.bankName,
                    bankCardNumber: res.data.withdrawalRecords.bankCardNumber,
                    withdrawalMethod: res.data.withdrawalRecords.withdrawalMethod,
                    preferredPhone: res.data.withdrawalRecords.preferredPhone,
                    withdrawalAmount: res.data.withdrawalRecords.withdrawalAmount,
                    handling_charge: res.data.withdrawalRecords.handling_charge,
                    actualAmount: res.data.withdrawalRecords.actualAmount,
                    createTime: res.data.withdrawalRecords.createTime,
                    processTime: res.data.withdrawalRecords.processTime,
                    status: res.data.withdrawalRecords.status,
                    }
                if (this.finance.status == 3) {
                    this.finance.paymentResult= res.data.withdrawalOtherRecords.paymentResult,
                    this.finance.failureReason= res.data.withdrawalOtherRecords.failureReason,
                    this.finance.supplementaryRemarks= res.data.withdrawalOtherRecords.supplementaryRemarks;
                } 
                })
              .catch(error => {
                    ElMessage.error('获取详情失败，请稍后重试');
                    console.error('获取提现记录详情失败:', error);
                });
        },
        getWithdrawalMethodText(method) {
            const methodMap = {
                '1': '银行卡提现',
                '2': '支付宝提现',
                '3': '微信提现'
            };
            return methodMap[method] || '';
        },
        getStatusText(status) {
            const statusMap = {
                '1': '提现中',
                '2': '提现成功',
                '3': '提现失败'
            };
            return statusMap[status] || '';
        }
    }
};
</script>

<style scoped>
.search-form {
    margin-bottom: 20px;
}

.dialog-content {
    padding: 20px;
}

.detail-item {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
}

.detail-item .label {
    width: 100px;
    margin-right: 10px;
    font-weight: 500;
}

.processing-opinion {
    margin-top: 20px;
}

.opinion-content {
    margin-left: 110px;
}

.opinion-label {
    margin-right: 10px;
}

.info-box {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100px;
    background-color: #f9a94a;
    color: #fff;
    font-size: 10px;
    border-radius: 5px;
    margin-top: 20px;
    padding: 10px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}
.custom-button-primary {
  background-color: #1890ff; /* 新的背景颜色 */
  border-color: #1890ff; /* 新的边框颜色 */
  color: white; /* 文字颜色 */
  border-radius: 4px; /* 边框圆角 */
  padding: 8px 16px; /* 内边距 */
  margin-right: 10px; /* 按钮之间的间距 */
}

.custom-button-info {
  background-color: #6699ff; /* 新的背景颜色 */
  border-color: #6699ff; /* 新的边框颜色 */
  color: white; /* 文字颜色 */
  border-radius: 4px; /* 边框圆角 */
  padding: 8px 16px; /* 内边距 */
}
</style>